let url = "http://localhost:8083"
// let url = "http://10.10.110.17:8084"
// let url = "http://223.100.141.246:58084"
// let url = "http://10.10.110.17:8083"

import {login} from '@/utils/api.js'
export default function request(options) {
  const token = uni.getStorageSync('token');
  return new Promise((resolve, reject) => {
    uni.request({
      url: url + options.url,
      header: {
        'Authorization': token
      },
      method: options.method || 'POST',
      data: options.data || {},
	  
      success: (res) => {
        // 处理 HTTP 层错误（非200）
        if (res.statusCode !== 200) {
          return reject(new Error(`HTTP错误: ${res.statusCode}`));
        }

        // 处理后端业务状态码
        const data = res.data;
        switch (data.status) {
          case 200:
            resolve(res);
            break;

          case 401:
          case 501:
            handleReLogin();
            reject(new Error('登录过期，请重新登录'));
            break;

          case 500:
            uni.showToast({
              title: data.msg || '服务器异常',
              icon: 'none'
            });
            reject(new Error(data.msg || '服务器异常'));
            break;

          default:
			if (res.statusCode === 200){
				 resolve(res);
			}
            // 其他未知状态，默认也拒绝
            reject(new Error(data.msg || '未知错误'));
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

function handleReLogin() {
  const username = uni.getStorageSync('userName');
  const password = uni.getStorageSync('userPsw');

  if (!username || !password) {
    uni.removeStorageSync('token');
    uni.showToast({ title: '请重新登录', icon: 'none' });
    setTimeout(() => {
      uni.navigateTo({ url: '/pages/login/login' });
    }, 1000);
    return;
  }

  login({ username, password }).then(res => {
    if (res.data.status === 200) {
      uni.setStorageSync('token', res.data.token);
    } else {
      uni.removeStorageSync('token');
      uni.showToast({ title: '请重新登录', icon: 'none' });
      setTimeout(() => {
        uni.navigateTo({ url: '/pages/login/login' });
      }, 1000);
    }
  });
}
